﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.IO;

namespace ImageUploader.domain
{
    public class ImageOperations
    {
        public static Image GetImageFromByteArray(byte[] byteArrayIn)
        {
            MemoryStream ms = new MemoryStream(byteArrayIn);
            Image returnImage;
            try
            {
                returnImage = Image.FromStream(ms);
            }
            catch (Exception excep)
            {
                return null;
            }

            return returnImage;
        }

        public static byte[] GetByteArrayFromJpgImage(Image img)
        {
            MemoryStream ms = new MemoryStream();
            img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            return ms.ToArray();
        }

        public static byte[] GetByteArrayFromImagePath(string path)
        {
            return GetByteArrayFromJpgImage(Image.FromFile(path));
        }

        public static Image GetJpgImageFromPath(string path)
        {
            string extention = new FileInfo(path).Extension;
            Image img = Image.FromFile(path);
            if (img.Width != 96 || img.Height != 96    | !img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Jpeg)
                    | !(extention.Equals(".jpg", StringComparison.CurrentCultureIgnoreCase) || extention.Equals(".jpeg", StringComparison.CurrentCultureIgnoreCase)))
                throw new Exception("Wrong format, the image should be a 96 * 96 JPG-file.");
            return img;
        }
    }
}
